﻿using FreeSql;

using GCC.Container.Abstracts;

namespace Z.ServerTest
{
    public class DBManager : IDBManager
    {

        public static readonly DBManager Instance = new();
        private readonly IFreeSql? _localDB;
        private readonly IFreeSql? _localReadDB;
        private readonly IFreeSql? _globalDB;
        private readonly IFreeSql? _globalReadDB;

        private DBManager()
        {
            var globalDBType = Environment.GetEnvironmentVariable("globalDBType");
            var localDBType = Environment.GetEnvironmentVariable("localDBType");
            if (int.TryParse(globalDBType, out var globalType))
            {
                var dbStr = Environment.GetEnvironmentVariable("globalDB");
                var dbReadStr = Environment.GetEnvironmentVariable("globalReadDB");
                var dbType = (DataType)globalType;
                if (!string.IsNullOrWhiteSpace(dbStr))
                {
                    try
                    {
                        _globalDB = new FreeSqlBuilder().UseConnectionString(dbType, dbStr).Build();
                    }
                    catch
                    {
                        _globalDB = null;
                    }
                }
                if (!string.IsNullOrWhiteSpace(dbReadStr))
                {
                    try
                    {
                        _globalReadDB = new FreeSqlBuilder().UseConnectionString(dbType, dbReadStr).Build();
                    }
                    catch
                    {
                        _globalReadDB = null;
                    }
                }
            }


            if (int.TryParse(localDBType, out var localType))
            {
                var dbStr = Environment.GetEnvironmentVariable("localDB");
                var dbReadStr = Environment.GetEnvironmentVariable("localReadDB");
                var dbType = (DataType)localType;
                if (!string.IsNullOrWhiteSpace(dbStr))
                {
                    try
                    {
                        _localDB = new FreeSqlBuilder().UseConnectionString(dbType, dbStr).Build();
                    }
                    catch
                    {
                        _localDB = null;
                    }
                }
                if (!string.IsNullOrWhiteSpace(dbReadStr))
                {
                    try
                    {
                        _localReadDB = new FreeSqlBuilder().UseConnectionString(dbType, dbReadStr).Build();
                    }
                    catch
                    {
                        _localReadDB = null;
                    }
                }
            }
        }

        IFreeSql? IDBManager.LocalDB { get => _localDB; }
        IFreeSql? IDBManager.LocalReadDB { get => _localReadDB; }
        IFreeSql? IDBManager.GlobalDB { get => _globalDB; }
        IFreeSql? IDBManager.GlobalReadDB { get => _globalReadDB; }
    }
}
